package com.sinosoft.modules.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.impl.AdaptorErrorContext;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.sinosoft.common.action.BaseAction;
import com.sinosoft.common.datatype.DateTime;
import com.sinosoft.common.util.ContentType;
import com.sinosoft.common.web.filter.BaseFilter;
import com.sinosoft.common.web.filter.UserLoginFilter;
import com.sinosoft.domain.base.BaseFile;

/**
 * 文件上传
 * @author unhappydepig 
 * @mail yqw8912@163.com
 * @time 2015-5-20 下午7:29:44
 */
@IocBean
@At("/common/file")
@Filters({ @By(type = UserLoginFilter.class), @By(type = BaseFilter.class) })
public class FileAction extends BaseAction {
    @Inject
    protected UploadAdaptor upload;
    /**
     * 文件上传
     * @param fileid
     * @param errCtx
     * @param req
     * @return
     */
    @At
    @Ok("raw:html")
    @AdaptBy(type = UploadAdaptor.class, args = "ioc:upload")
    public String upload(@Param("file")TempFile fileid, AdaptorErrorContext errCtx,HttpServletRequest req) {
    	dao.create(BaseFile.class, false);
        Map<String, Object> js = new HashMap<String, Object>();
        try {
            File file = fileid.getFile();
        	BaseFile baseFile = new BaseFile();
        	String fileExt = Files.getSuffixName(file).toLowerCase();
        	String fileName = fileid.getMeta().getFileLocalName();
        	DateTime current = DateTime.current();
        	String filePath = daoUtil.getUserID()+"."+fileExt+"."+current.getYear()+"."+current.getMonth()+"."+current.getDay()+".";
            long len = fileid.getFile().length();
        	double fileSize = getFileSize(len, 8);
        	baseFile.setFileExt(fileExt);
        	baseFile.setFileName(fileName.toLowerCase().replaceAll("."+fileExt, ""));
        	baseFile.setFileSize(fileSize);
        	baseFile.setFilePath(filePath);
        	baseFile.setValid("1");
        	daoUtil.add(baseFile);        	
            Files.copy(file, new File(baseFile.getRealFilePath()));
        	Files.deleteFile(file);
    		js.put("filename", fileName);
    		js.put("fileid", baseFile.getFileId());
    		js.put("filesize", getFileSize(len, 8));
    		js.put("error", "");        	
        } catch (Exception e) {
            	e.printStackTrace();
                js.put("error", "错误：上传文件异常！");
                js.put("msg", "");
                return Json.toJson(js);
       }
        return Json.toJson(js);
    }
    /**
     * 文件下载
     * @param fileId
     * @param req
     * @param response
     */
    @At
    public void down(@Param("fileId")String fileId,HttpServletRequest req,HttpServletResponse response) {
    	dao.create(BaseFile.class, false);
    	BaseFile baseFile = new BaseFile();
    	baseFile.setFileId(fileId);
    	baseFile.setCreateBy(daoUtil.getUserID());
    	List<BaseFile> fileList = daoUtil.queryList(baseFile);
    	if(null==fileList||fileList.size()<=0){
    		ajaxDoneError(response, "文件不存在,或您没有权限下载此文件!");
    		return;
    	}
    	baseFile = fileList.get(0);
		BufferedInputStream br = null;
		OutputStream out = null;
		File f = new File(baseFile.getRealFilePath());
		try {
			br = new BufferedInputStream(new FileInputStream(f));
			byte[] buf = new byte[1024];
			int len = 0;
			response.reset(); 
			String contextType = ContentType.typeMap.get(baseFile.getFileExt());
			if(null==contextType||"".equals(contextType)){
				contextType = ContentType.typeMap.get("*");
			}
			response.setContentType(contextType);
			response.setHeader("Content-Disposition", "attachment; filename="+baseFile.getFileName()+"."+baseFile.getFileExt());
			out = response.getOutputStream();
			while ((len = br.read(buf)) != -1) {
				out.write(buf, 0, len);
				out.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
    		ajaxDoneError(response, e);
		} finally {
			try {
				br.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
	    		ajaxDoneError(response, e);
			}
		}    	
    }
    /**
     * 返回文件大小，单位MB
     *
     * @param filesize
     * @param scale
     * @return
     */
    private double getFileSize(long filesize, int scale) {
        BigDecimal bd1 = new BigDecimal(Long.toString(filesize));
        BigDecimal bd2 = new BigDecimal(Long.toString(1024));
        return bd1.divide
                (bd2, scale, BigDecimal.ROUND_HALF_UP).divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
